package vn.cuhanh.fragment;

import java.util.ArrayList;
import java.util.List;

import vn.cuhanh.ChooseGameActivity;
import vn.cuhanh.GameDetailActivity;
import vn.cuhanh.MainActivity;
import vn.cuhanh.R;
import vn.cuhanh.ShareActivity;
import vn.cuhanh.bean.Game;
import vn.cuhanh.bean.ShareInfo;
import vn.cuhanh.dialog.UpdatePhoneNoDialog;
import vn.cuhanh.dialog.ViewZingMeInfoDialog;
import vn.cuhanh.models.Model_CharInfo;
import vn.cuhanh.utils.HelperFunc;
import vn.cuhanh.utils.LoginHelper;
import vn.cuhanh.utils.ShareZingMe;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MenuFragment extends Fragment {
	private static String GA_CATEGORY = "Menu_fragment";
	public static final int MENU_UPDATE_PHONE_NO_REQUEST_CODE = 1561;
	
	public static final int[] DEFAULT_PAGES = new int[]{1,2,3,4,5,6,7,8};
	public static final int PAGE_CHAR_INFO = 1;
	public static final int PAGE_AWARD = 2;
	public static final int PAGE_NEWS = 3;
	public static final int PAGE_PLAY_TYPE = 4;
	public static final int PAGE_HERO = 5;
	public static final int PAGE_MINIGAME = 6;
	public static final int PAGE_LEADERBOARD = 7;
	public static final int PAGE_HELP = 8;
	
	private Context context;
	private Game appInfo;
	private int[] pages;
	private ArrayList<String> listPageName;
	private ArrayList<String> listPageImageName;
	private PageListAdapter pageListAdapter;
	private GameGridAdapter gameGridAdapter;
	private View view;

	public static MenuFragment getInstance(Context context) {
		return new MenuFragment(context);
	}
	
	public MenuFragment(){
		super();
		context = GameDetailActivity.gameDetailContext;
	}
	
	private MenuFragment(Context context) {
		super();
		this.context = context;
		
		if(ChooseGameActivity.games != null 
				&& (ChooseGameActivity.games instanceof ArrayList<?>) 
				&& !ChooseGameActivity.games.isEmpty()) {
			this.appInfo = ChooseGameActivity.current;
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.left_menu, null);
		
		ListView listPages = (ListView)view.findViewById(R.id.left_menu_list_pages);
		appInfo = ChooseGameActivity.current;
		pages = GameDetailActivity.getAvailablePages(appInfo.getPages());
		listPageName = getListPageName();
		listPageImageName = getListPageImageName();
		pageListAdapter = new PageListAdapter(this.context, R.id.left_menu_list_pages, R.layout.left_menu_page_item, listPageName, this.pages);
		listPages.setAdapter(pageListAdapter);
		HelperFunc.setListViewHeightBasedOnChildren(listPages);
		
		GridView gridGames = (GridView)view.findViewById(R.id.left_menu_grid_games);
		gameGridAdapter = new GameGridAdapter(this.context, R.layout.left_menu_game_item, ChooseGameActivity.games);
		gridGames.setAdapter(gameGridAdapter);
		
		TextView txtCurrentAppName = (TextView)view.findViewById(R.id.left_menu_current_game_name);
		txtCurrentAppName.setText(ChooseGameActivity.current.getAppName().toUpperCase());
		
		TextView txtLogin = (TextView)view.findViewById(R.id.left_menu_login);
		txtLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(context, GA_CATEGORY, "btn_login_press", "btn_login_press");
				final LoginHelper loginHelper = LoginHelper.getInstance();
				loginHelper.requestZingMeLogin(context, new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						restartGameDetail();
					}
				});
			}
		});
		
		TextView txtLogout = (TextView)view.findViewById(R.id.left_menu_logout);
		txtLogout.setOnClickListener(new OnClickListener() {
			
			public void logout() {
				LoginHelper loginHelper = LoginHelper.getInstance();
				loginHelper.logout(context);
				restartGameDetail();
			}
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(context, GA_CATEGORY, "btn_logout_press", "btn_logout_press");
				HelperFunc.showSimpleAlertDialog(context, context.getResources().getString(R.string.logout), context.getResources().getString(R.string.confirm_logout), context.getResources().getString(R.string.bt_ok_title), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						HelperFunc.trackEvent(context, GA_CATEGORY, "btn_confirm_logout_press", "btn_confirm_logout_press");
						logout();
					}
				}, context.getResources().getString(R.string.bt_cancel_title), null, false);
			}
		});
		TextView txtViewZingMeInfo = (TextView)view.findViewById(R.id.left_menu_account_info);
		txtViewZingMeInfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(context, GA_CATEGORY, "btn_view_zing_me_info_press", "btn_view_zing_me_info_press");
				Intent intent = new Intent(context, ViewZingMeInfoDialog.class);
				startActivity(intent);
			}
		});
		TextView txtUpdatePhoneNo = (TextView)view.findViewById(R.id.left_menu_update_phone_no);
		txtUpdatePhoneNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HelperFunc.trackEvent(context, GA_CATEGORY, "btn_update_phone_no_press", "btn_update_phone_no_press");
				Intent intent = new Intent(context, UpdatePhoneNoDialog.class);
				startActivityForResult(intent, MENU_UPDATE_PHONE_NO_REQUEST_CODE);
			}
		});
		updateUserGroup();
		return view;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode != MENU_UPDATE_PHONE_NO_REQUEST_CODE) {
			return;
		}
		if(resultCode != Activity.RESULT_OK) {
			return;
		}
		if(data == null || !data.hasExtra("haveChange") || !data.getExtras().getBoolean("haveChange")) {
			return;
		}
		if(CharacterInfoFragment.charInfo == null) {
			Thread thread = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Model_CharInfo.loadCharInfoFromInternet(context);
//					if(CharacterInfoFragment.charInfo != null) {
						((Activity)context).runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								showSharePhoneNoAcivity();
							}
						});
//					}
				}
			});
			thread.start();
			return;
		}
		showSharePhoneNoAcivity();
	}
	
	public void showSharePhoneNoAcivity() {
		ShareActivity.shareInfo = new ShareInfo(
				ShareZingMe.getRandomFunnyPhrase(context), 
				context.getResources().getString(R.string.phone_no_share_title), 
				context.getResources().getString(R.string.phone_no_share_description)
					.replace("char_name", CharacterInfoFragment.getCharName()),
				context.getResources().getString(R.string.phone_no_share_imgurl), 
				context.getResources().getString(R.string.phone_no_share_local_img),
				context.getResources().getString(R.string.phone_no_share_link), 
				context.getResources().getString(R.string.phone_no_share_state),
				0);
		Intent intent = new Intent(context, ShareActivity.class);
		startActivity(intent);
	}

	public void restartGameDetail() {
		Intent intent = new Intent(context, GameDetailActivity.class);
		intent.putExtra("checkForZingMeInfoChanges", true);
		startActivity(intent);
	}
	
	public void updateUserGroup() {
		View txtUserInfo = (View)(view.findViewById(R.id.left_menu_account_info).getParent().getParent());
		View txtUpdatePhoneNo = (View)(view.findViewById(R.id.left_menu_update_phone_no).getParent().getParent());
		View txtLogout = (View)(view.findViewById(R.id.left_menu_logout).getParent().getParent());
		View txtLogin = (View)(view.findViewById(R.id.left_menu_login).getParent().getParent());
		if(MainActivity.isLogin) {
			txtUserInfo.setVisibility(View.VISIBLE);
			txtUpdatePhoneNo.setVisibility(View.VISIBLE);
			txtLogout.setVisibility(View.VISIBLE);
			txtLogin.setVisibility(View.GONE);
		} else {
			txtUserInfo.setVisibility(View.GONE);
			txtUpdatePhoneNo.setVisibility(View.GONE);
			txtLogout.setVisibility(View.GONE);
			txtLogin.setVisibility(View.VISIBLE);
		}
	}
	
	public ArrayList<String> getListPageName(){
		ArrayList<String> listPageName = new ArrayList<String>();
		String[] pageNames = context.getResources().getStringArray(R.array.menus_text);
		for (int pageId : this.pages) {
			listPageName.add(pageNames[pageId - 1]);
		}
		return listPageName;
	}
	public ArrayList<String> getListPageImageName() {
		ArrayList<String> listPageImageName = new ArrayList<String>();
		String[] pageNames = context.getResources().getStringArray(R.array.menus_image);
		for (int pageId : this.pages) {
			listPageImageName.add(pageNames[pageId - 1]);
		}
		return listPageImageName;
	}
	
	public void showPage(int pageId){
		if(this.appInfo == null || ChooseGameActivity.current == null) {
			//TODO Log error
			return;
		}
		ChooseGameActivity.currentPage = pageId;
		if(this.appInfo.getId() == ChooseGameActivity.current.getId()) {
			//Scroll to page
			int pagePosition = 0;
			for(int i = 0; i < this.pages.length; i++) {
				if(this.pages[i] == pageId) {
					pagePosition = i;
					break;
				}
			}
			try {
				((GameDetailActivity)this.context).getSlidingMenu().showContent();
				((GameDetailActivity)this.context).showPage(pagePosition);
				return;
			} catch(ClassCastException e) {
				HelperFunc.readStackTrace(e);
			} catch (Exception e) {
				// TODO: handle exception
				HelperFunc.readStackTrace(e);
			}
		}
		ChooseGameActivity.current = this.appInfo;
		//Reload intent
		Intent intent = new Intent(this.context, GameDetailActivity.class);
		intent.putExtra("checkForZingMeInfoChanges", false);
		startActivity(intent);
	}
	
	public void reloadGame(Game newGame) {
		this.appInfo = newGame;
		if(gameGridAdapter != null) {
			gameGridAdapter.notifyDataSetChanged();
		}
		if(pageListAdapter != null) {
			pageListAdapter.clear();
			pages = GameDetailActivity.getAvailablePages(appInfo.getPages());
			listPageName = getListPageName();
			listPageImageName = getListPageImageName();
			pageListAdapter.notifyDataSetChanged();
			
			ListView listPages = (ListView)view.findViewById(R.id.left_menu_list_pages);
			HelperFunc.setListViewHeightBasedOnChildren(listPages);
		}
		if(view != null) {
			TextView txtAppName = (TextView)view.findViewById(R.id.left_menu_current_game_name);
			txtAppName.setText(newGame.getAppName().toUpperCase());
		}
	}
	
	public class PageListAdapter extends ArrayAdapter<String> {
		public PageListAdapter(Context context, int resource,
				int textViewResourceId, List<String> objects, int[] pages) {
			super(context, resource, textViewResourceId, objects);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public int getCount() {
			return pages.length;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.left_menu_page_item, null);
			}
			
			TextView pageName = (TextView)convertView.findViewById(R.id.pageName);
			pageName.setText(listPageName.get(position));
			ImageView pageImage = (ImageView)convertView.findViewById(R.id.left_menu_page_image);
			int resId = context.getResources().getIdentifier(listPageImageName.get(position), "drawable", context.getPackageName());
			pageImage.setImageResource(resId);
			final int pageId = pages[position];
			pageName.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					HelperFunc.trackEvent(context, GA_CATEGORY, "menu_item_press", "menu_item_" + pageId + "press");
					showPage(pageId);
				}
			});
			
			return convertView;
		}
	}
	
	public class GameGridAdapter extends ArrayAdapter<Game> {

		public GameGridAdapter(Context context, int textViewResourceId, List<Game> games) {
			super(context, textViewResourceId, games);
			// TODO Auto-generated constructor stub
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null) {
				LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				convertView = inflater.inflate(R.layout.left_menu_game_item, null);
			}
			
			final Game gameInfo = getItem(position);
			ImageView appImage = (ImageView)convertView.findViewById(R.id.gameImage);
			appImage.setImageResource(context.getResources().getIdentifier(gameInfo.getNav_image(), "drawable", context.getPackageName()));
//			UrlImageViewHelper.setUrlDrawable(appImage, gameInfo.getImage());
			
			appImage.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					reloadGame(gameInfo);
				}
			});
			
			return convertView;
		}
	}
}
